package com.zhangkunhao.notes.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 替换HttpServlet,根据请求的最后一段路径来进行方法分发
 *
 * @author 20642
 */
public class BaseDaoServlet extends HttpServlet {
    /**
     * 根据请求的最后一段路径来进行方法分发
     *
     * @param req:
     * @param resp:
     * @throws ServletException:
     * @throws IOException:
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //不能调用父类的方法,否则还是按请求方式进行方法分发
        //super.service(req, resp);

        //1.获取请求路径
        //brand-case/brand/selectAll
        String uri = req.getRequestURI();

        //2.获取最后一段路径的方法名
        int index = uri.lastIndexOf('/');
        String methodName = uri.substring(index + 1);

        //3.执行方法
        // BrandServlet或UserServlet=>this
        //3.1 获取BrandServlet或UserServlet的字节码文件
        Class<? extends BaseDaoServlet> aClass = this.getClass();

        try {
            //3.2 获取方法
            Method method = aClass.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //3.3 执行
            method.invoke(this, req, resp);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }

    }
}
